/**
 * 获取视频基本信息
 *
 * @param videoSrc {string} 视频地址
 * @returns {Promise<unknown>}
 */
const getVideoBasicInfo = (videoSrc) => {
  return new Promise((resolve, reject) => {
    const video = document.createElement('video');
    video.src = videoSrc;
    // 视频一定要添加预加载
    video.preload = 'auto';
    // 视频一定要同源或者必须允许跨域
    video.crossOrigin = 'Anonymous';
    // 监听：异常
    video.addEventListener('error', (error) => {
      reject(error);
    });
    // 监听：加载完成基本信息,设置要播放的时常
    video.addEventListener('loadedmetadata', () => {
      const videoInfo = {
        video,
        width: video.videoWidth,
        height: video.videoHeight,
        duration: video.duration
      };
      resolve(videoInfo);
    });
  });
};

/**
 * 将获取到的视频信息，转化为图片地址
 *
 * @param videoInfo {object} 视频信息
 * @returns {Promise<unknown>}
 */
const getVideoPosterInfo = (videoInfo) => {
  return new Promise((resolve) => {
    const { video, width, height } = videoInfo;
    video.addEventListener('canplay', () => {
      const canvas = document.createElement('canvas');
      canvas.width = width;
      canvas.height = height;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(video, 0, 0, width, height);
      const posterUrl = canvas.toDataURL('image/jpg');
      resolve({ posterUrl });
    });
  });
};

/**
 * 获取视频第一帧图片
 *
 * @param videoUrl {string} 视频地址
 * @returns {string | undefined}
 */
async function getVideoFirstFrame(videoUrl) {
  const videoInfo = await getVideoBasicInfo(videoUrl);
  const posterInfo = await getVideoPosterInfo(videoInfo);
  return posterInfo?.posterUrl;
}

const VideoUtil = {
  getVideoFirstFrame
};

export default VideoUtil;
